<template>
	<view class="header bgf">
		<view class="nav">
			<u-navbar
			title="订单"
			:autoBack="true"
			:background="{
			background:'transparent'
			}"
			:border-bottom="false"
			titleSize="28rpx" titleColor="#333"
			back-icon-color="#333"
			:isFixed="false"
			:is-back="false"
			/>
		</view>

		<view class="tabs">
			<u-tabs :list="tab.list" :is-scroll="false" :current="tab.current" @change="tab.change"
			active-color="#E40417"
			barWidth="82"
			barHeight="6"
			bg-color="transparent"
			inactive-color="#666"
			ref="uTabsE"
			></u-tabs>
		</view>
		
		<scroll-view scroll-x="true" class="timeselect p30" v-if="tab.current == 1">
			<view class="item t-flex colum between" v-for="item,index in status.dateList" :key="index"
			:class="{'active':index == status.date}"
			@click="status.change(index)"
			>
				<view class="f36  bold">
					{{item.str}}
				</view>
				<view class="">
					{{index==0?"今天":index==1?'明天':index==2?"后天":weekLabel[item.week]}}
				</view>
				<view class="f24 c9">
					{{status.counts[index]?.count || 0}}单
				</view>
			</view>
		</scroll-view>
	</view>

	
	<view class="container p30">
		<view class="c3 t-flex between" v-if="tab.current == 1">
			<view class="">
				{{new Date().getFullYear()}} {{status.dateList[status.date].str}}（{{weekLabel[status.dateList[status.date].week]}}）
			</view>
			<view class="">
				{{status.counts[status.date]?.count || 0}}单
			</view>
		</view>
		
		<template v-if="tab.current">
			<workersOrder v-for="item in order.data.value" :key="item.id" :data="item"
			@contract="contract.open"
			></workersOrder>
		</template>
		<template v-else>
			<publicOrderVue v-for="item in publicOrder.data.value" :key="item.id" :data="item"
			@take="take"
			></publicOrderVue>
		</template>
		<empty :msg="tab.current?'暂无相关订单':'暂无可接取订单'" v-if="tab.current?!order.data.value.length:!publicOrder.data.value.length"></empty>
	</view>
	
	
	<uploadOption @success="contract.confirm" ref="uploadOptionE"></uploadOption>
</template>

<script setup lang="ts">
import publicOrderVue from '../../../components/publicOrder/publicOrder.vue';
import { reactive,onUnmounted,ref,onMounted } from 'vue';
import { getTime, miniPre, previewImg, showToast, tRequest, usePaging } from '../../../lib/ts/util';
import { dfwGetSfTime, uploadHt } from '../../../api';


	const publicOrder = usePaging('/api/master/OrderList')
	const order = usePaging('/api/master/GoodsOrderList')
	const uploadOptionE = ref()
	const uTabsE = ref()
	
	onUnmounted(()=>{
		uni.$off('orderPageOnPullDownRefresh')
		uni.$off('orderPageOnReachBottom')
	})
	uni.$on('orderPageOnPullDownRefresh', async ()=>{
		status.counts = await dfwGetSfTime({
			s_day:getTime(status.dateList[0].timestamp,2),
			e_day:getTime(status.dateList[status.dateList.length-1].timestamp,2)
		})
		reload()
	})
	uni.$on('orderPageOnReachBottom',()=>{
		getMore()
	})
	onMounted(()=>{
		setTimeout(()=>{
			uTabsE.value.init()
		},100)
	})
	
		

	let tab = reactive({
		list:[{name:'订单池',id:0},{name:'待服务',id:1},{name:'待评价',id:2},{name:'已评价',id:5}],
		current:0,
		change(e:number){
			tab.current = e
			reload()
		}
	})
	
	
	
	let weekLabel = ['周日','周一','周二','周三','周四','周五','周六']
	let status = reactive({
		date:0,
		dateList:[],
		counts:[],
		change(e){
			status.date = e
			reload()
		}
	})
	
	
	const getDateList = async ()=>{
		let arr = []
		let now = new Date()
		arr[0] = +now
		let i = 1
		while(i++<=7){
			let time = now.setDate(now.getDate()+1)
			arr.push(time)
		}
		arr.forEach(item=>{
			let date = new Date(item)
			status.dateList.push({
				week:date.getDay(),
				month:date.getMonth()+1,
				day:date.getDate(),
				timestamp:Math.floor(item/1000),
				str:`${ (date.getMonth()+1+'').padStart(2,'0')}-${(date.getDate()+'').padStart(2,'0')}`
			})
		})
		status.counts = await dfwGetSfTime({
			s_day:getTime(status.dateList[0].timestamp,2),
			e_day:getTime(status.dateList[status.dateList.length-1].timestamp,2)
		})
	}
	getDateList()
	
	//获取近期订单数量

	
	
	const reload = ()=>{
		if(tab.current){
			order.reload({
				status:tab.list[tab.current].id,
				search_to_day:`${new Date().getFullYear()}-${status.dateList[status.date].str}`
			})
		}else{
			publicOrder.reload()
		}
	}
	reload()
	const getMore = ()=>{
		if(tab.current){
			order.getMore({
				status:tab.list[tab.current].id,
				search_to_day:`${new Date().getFullYear()}-${status.dateList[status.date].str}`
			})
		}else{
			publicOrder.getMore()
		}
	}
	
	
	//合同
	let contract = reactive({
		target:'',
		open(e){
			contract.target = e.id
			if(e.ht_info){ //查看合同
				miniPre(e.ht_info)
			}else{ //上传合同
				uploadOptionE.value.open()
			}
		},
		async confirm(ht_info:string){
			let res = await uploadHt({
				order_detail_id:contract.target,
				ht_info
			})
			showToast(res.msg)
			reload()
		}
	})
	
	
	//预览
	const getFileType = (str:string)=>{
	    return str.split('.').reverse()[0]
	}
	const pre = (e)=>{
	    let  fileType = getFileType(e)
		if(['wav','webm','mp4'].includes(fileType)){
			uni.navigateTo({
				url:'/pages/public/video?url='+e
			})
		}else if(fileType == 'pdf'){
			uni.showLoading({
				mask:true,
				title:'正在下载...'
			})
			uni.downloadFile({
				url:e,
				success(e) {
					uni.openDocument({
						filePath:e.tempFilePath,
					})
				},
				fail(e) {
					console.log(e,'fail')
				},
				complete() {
					uni.hideLoading()
				}
			})
		}else if(['jpg','png','jpeg','webp'].includes(fileType)){
			previewImg(e,0)
		} else{
			uni.showModal({
				title:'提示',
				content:'不支持在线预览该类型的文件,您可以选择下载到本地',
				confirmText:'复制链接',
				success(e) {
					if(e.confirm){
						uni.setClipboardData({
							data:e,
						})
					}
				}
			})
		}
	}
	
	//接单
	const take = (target)=>{
		uni.showModal({
			title:'提示',
			content:'是否接单？',
			success(e) {
				if(e.confirm){
					tRequest('post','/api/master/SfToOrder',{
						order_id:target.id
					}).then( async res=>{
						showToast(res.msg)
						status.counts = await dfwGetSfTime({
							s_day:getTime(status.dateList[0].timestamp,2),
							e_day:getTime(status.dateList[status.dateList.length-1].timestamp,2)
						})
						reload()
					})
				}
			}
		})
		
	}
	
</script>

<style scoped lang="scss">
	.bg{
		width: 100%;
		position: absolute;
	}
	
	.header{
		position: sticky;
		top: 0;
		.nav{
			background: linear-gradient( 180deg, #FFEDEB 0%, #FFFFFF 100%);
		}
	}
	
	.timeselect{
		white-space: nowrap;
		box-sizing: border-box;
		.item{
			display: inline-flex;
			width: 180rpx;
			height: 160rpx;
			background: #F6F6F6;
			border-radius: 12rpx;
			padding: 14rpx 0;
			margin-right: 20rpx;
		}
		.item.active{
			background-color: #FFE7E7;
			color: $main-color;
			.c9{
				color: $main-color;
			}
		}
	}
	
	
	
	
	
</style>
